package com.tool;

import java.util.ArrayList;
import java.util.List;

import javax.swing.table.AbstractTableModel;
import com.util.Shelf;

public class ShelfTableModel extends AbstractTableModel {
	private static final String[] COLUMN_NAMES = { "X", "Y", "Beg. ID",
			"End. ID" };
	private static final Class<?>[] COLUMN_CLASSES = { Double.class,
			Double.class, String.class, String.class };

	static {
		assert COLUMN_NAMES.length == COLUMN_CLASSES.length;
	}

	private final List<Shelf> shelves = new ArrayList<Shelf>();

	public ShelfTableModel(ArrayList<Shelf> shelves) {
		if (shelves != null && !shelves.isEmpty())
			for (Shelf s : shelves) {
				addShelf(s);
			}
	}

	// TableModel methods delegate through to collection of MyBusinessObject.
	public int getColumnCount() {
		return COLUMN_NAMES.length;
	}

	public String[] getColumnNames() {
		return COLUMN_NAMES;
	}

	public Class<?>[] getColumnClasses() {
		return COLUMN_CLASSES;
	}

	public Object getValueAt(int row, int col) {
		Object ret;
		Shelf shelf = shelves.get(row);

		switch (col) {
		case 0:
			ret = shelf.getX();
			break;
		case 1:
			ret = shelf.getY();
			break;
		case 2:
			ret = shelf.getBegId();
			break;
		case 3:
			ret = shelf.getEndId();
			break;
		default:
			throw new IllegalArgumentException("Invalid column index: " + col);
		}

		return ret;
	}

	// Additional methods for updating the collection.
	public void addShelf(Shelf shelf) {
		shelves.add(shelf);
		int i = shelves.size() - 1;
		fireTableRowsInserted(i, i);
	}

	public Shelf removeShelf(int i) {
		Shelf s = shelves.get(i);
		shelves.remove(i);

		this.fireTableRowsDeleted(i, i);
		return s;
	}

	public boolean isCellEditable(int row, int column) {
		if (column > 1) {
			return true;
		} else
			return false;
	}

	public void setValueAt(Object value, int row, int col) {
		Shelf s = shelves.get(row);
		switch (col) {
		case 2:
			s.setBegId((String) value);
			break;
		case 3:
			s.setEndId((String) value);
			break;
		default:
			throw new IllegalArgumentException("Invalid column index: " + col);
		}

		shelves.get(row).copy(s);

		this.fireTableCellUpdated(row, col);
	}

	@Override
	public int getRowCount() {
		return shelves.size();

	}

	public Shelf getRow(int row) {

		return shelves.get(row);
	}
}